'use client'

import { useState, useEffect } from 'react'
import { useRouter } from 'next/navigation'
import { Plus, Search, Filter, MoreHorizontal, Edit, Trash2, Eye, Loader2, FileText, CheckCircle, Archive, User } from 'lucide-react'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Badge } from '@/components/ui/badge'
import { 
  DropdownMenu, 
  DropdownMenuContent, 
  DropdownMenuItem, 
  DropdownMenuTrigger 
} from '@/components/ui/dropdown-menu'
import { knowledgeAPI } from '@/lib/api'
import { toast } from 'sonner'
import { KnowledgeBase } from '@/lib/types'
import { 
  CompactLayout, 
  CompactHeading, 
  CompactSubheading,
  CompactGrid,
  CompactCard 
} from '@/components/ui/compact-layout'

export default function KnowledgeManagement() {
  const router = useRouter()
  const [articles, setArticles] = useState<KnowledgeBase[]>([])
  const [searchQuery, setSearchQuery] = useState('')
  const [selectedCategory, setSelectedCategory] = useState('all')
  const [selectedStatus, setSelectedStatus] = useState('all')
  const [isLoading, setIsLoading] = useState(true)
  const [isSubmitting, setIsSubmitting] = useState(false)

  const categories = ['all', '前端开发', '后端开发', '数据库', '移动开发', '运维部署']
  const statuses = ['all', 'DRAFT', 'PUBLISHED', 'ARCHIVED']

  // 获取文章列表
  const fetchArticles = async () => {
    try {
      setIsLoading(true)
      const response = await knowledgeAPI.getKnowledgeBases()
      setArticles(response.knowledgeBases || [])
    } catch (error: any) {
      console.error('Failed to fetch articles:', error)
      toast.error(error.message || '获取文章列表失败')
    } finally {
      setIsLoading(false)
    }
  }

  // 更新文章状态
  const updateArticleStatus = async (articleId: string, status: string) => {
    try {
      setIsSubmitting(true)
      await knowledgeAPI.updateKnowledgeBaseStatus(articleId, status)
      toast.success('文章状态更新成功')
      fetchArticles() // 重新获取文章列表
    } catch (error: any) {
      console.error('Failed to update article status:', error)
      toast.error(error.message || '更新文章状态失败')
    } finally {
      setIsSubmitting(false)
    }
  }

  // 删除文章
  const deleteArticle = async (articleId: string) => {
    if (!confirm('确定要删除这篇文章吗？此操作不可撤销。')) {
      return
    }

    try {
      setIsSubmitting(true)
      await knowledgeAPI.deleteKnowledgeBase(articleId)
      toast.success('文章删除成功')
      fetchArticles() // 重新获取文章列表
    } catch (error: any) {
      console.error('Failed to delete article:', error)
      toast.error(error.message || '删除文章失败')
    } finally {
      setIsSubmitting(false)
    }
  }

  // 初始化加载
  useEffect(() => {
    fetchArticles()
  }, [])

  const filteredArticles = articles.filter(article => {
    const matchesSearch = article.title.toLowerCase().includes(searchQuery.toLowerCase()) ||
                         article.author.username.toLowerCase().includes(searchQuery.toLowerCase())
    const matchesCategory = selectedCategory === 'all' || article.category?.name === selectedCategory
    const matchesStatus = selectedStatus === 'all' || article.status === selectedStatus
    
    return matchesSearch && matchesCategory && matchesStatus
  })

  const getStatusBadge = (status: string) => {
    switch (status) {
      case 'PUBLISHED':
        return <Badge variant="default" className="bg-green-100 text-green-800">已发布</Badge>
      case 'DRAFT':
        return <Badge variant="secondary">草稿</Badge>
      case 'ARCHIVED':
        return <Badge variant="outline">已归档</Badge>
      default:
        return <Badge variant="outline">{status}</Badge>
    }
  }

  if (isLoading) {
    return (
      <div className="flex items-center justify-center min-h-[400px]">
        <div className="flex items-center space-x-2">
          <Loader2 className="h-6 w-6 animate-spin" />
          <span>加载文章数据中...</span>
        </div>
      </div>
    )
  }

  return (
    <CompactLayout spacing="md" padding="md">
      {/* 页面标题 */}
      <div className="flex items-center justify-between">
        <div>
          <CompactHeading>知识库管理</CompactHeading>
          <CompactSubheading>管理知识库文章和内容</CompactSubheading>
        </div>
        <Button onClick={() => router.push('/knowledge/create')}>
          <Plus className="h-4 w-4 mr-2" />
          新建文章
        </Button>
      </div>

      {/* 搜索和筛选 */}
      <CompactCard>
        <div className="flex items-center justify-between mb-3">
          <h3 className="text-lg font-semibold">搜索和筛选</h3>
        </div>
        <div className="space-y-3">
          <div className="flex flex-col sm:flex-row gap-3">
            <div className="flex-1">
              <div className="relative">
                <Search className="absolute left-2 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground" />
                <Input
                  placeholder="搜索文章标题或作者..."
                  value={searchQuery}
                  onChange={(e) => setSearchQuery(e.target.value)}
                  className="pl-8 h-8"
                />
              </div>
            </div>
            <div className="flex gap-2">
              <select
                value={selectedCategory}
                onChange={(e) => setSelectedCategory(e.target.value)}
                className="px-3 py-2 border border-input rounded-md bg-background text-sm h-8"
              >
                {categories.map(category => (
                  <option key={category} value={category}>
                    {category === 'all' ? '全部分类' : category}
                  </option>
                ))}
              </select>
              <select
                value={selectedStatus}
                onChange={(e) => setSelectedStatus(e.target.value)}
                className="px-3 py-2 border border-input rounded-md bg-background text-sm h-8"
              >
                {statuses.map(status => (
                  <option key={status} value={status}>
                    {status === 'all' ? '全部状态' : 
                     status === 'PUBLISHED' ? '已发布' :
                     status === 'DRAFT' ? '草稿' : '已归档'}
                  </option>
                ))}
              </select>
            </div>
          </div>
        </div>
      </CompactCard>

      {/* 文章统计 */}
      <CompactGrid cols={4}>
        <CompactCard>
          <div className="flex items-center space-x-2">
            <FileText className="h-4 w-4 text-blue-600" />
            <div>
              <p className="text-xs text-muted-foreground">总文章数</p>
              <p className="text-xl font-bold">{articles.length}</p>
            </div>
          </div>
        </CompactCard>
        <CompactCard>
          <div className="flex items-center space-x-2">
            <CheckCircle className="h-4 w-4 text-green-600" />
            <div>
              <p className="text-xs text-muted-foreground">已发布</p>
              <p className="text-xl font-bold">{articles.filter(a => a.status === 'PUBLISHED').length}</p>
            </div>
          </div>
        </CompactCard>
        <CompactCard>
          <div className="flex items-center space-x-2">
            <Edit className="h-4 w-4 text-yellow-600" />
            <div>
              <p className="text-xs text-muted-foreground">草稿</p>
              <p className="text-xl font-bold">{articles.filter(a => a.status === 'DRAFT').length}</p>
            </div>
          </div>
        </CompactCard>
        <CompactCard>
          <div className="flex items-center space-x-2">
            <Archive className="h-4 w-4 text-gray-600" />
            <div>
              <p className="text-xs text-muted-foreground">已归档</p>
              <p className="text-xl font-bold">{articles.filter(a => a.status === 'ARCHIVED').length}</p>
            </div>
          </div>
        </CompactCard>
      </CompactGrid>

      {/* 文章列表 */}
      <CompactCard>
        <div className="flex items-center justify-between mb-3">
          <h3 className="text-lg font-semibold">文章列表 ({filteredArticles.length})</h3>
        </div>
        {filteredArticles.length === 0 ? (
          <div className="text-center py-8 text-muted-foreground">
            暂无文章数据
          </div>
        ) : (
          <div className="space-y-3">
            {filteredArticles.map((article) => (
              <div
                key={article.id}
                className="flex items-center justify-between p-3 border border-border rounded-lg hover:bg-accent/50 transition-colors"
              >
                <div className="flex items-center space-x-3">
                  <div className="w-10 h-10 bg-muted rounded-lg flex items-center justify-center">
                    <FileText className="h-5 w-5 text-muted-foreground" />
                  </div>
                  <div>
                    <div className="flex items-center space-x-2">
                      <h3 className="text-base font-medium">{article.title}</h3>
                      {getStatusBadge(article.status)}
                      {article.category && (
                        <Badge variant="outline" className="text-xs">
                          {article.category.name}
                        </Badge>
                      )}
                    </div>
                    <div className="flex items-center space-x-3 mt-1 text-xs text-muted-foreground">
                      <span className="flex items-center space-x-1">
                        <User className="h-3 w-3" />
                        <span>{article.author.username}</span>
                      </span>
                      <span>创建: {new Date(article.createdAt).toLocaleDateString()}</span>
                      {article.updatedAt && (
                        <span>更新: {new Date(article.updatedAt).toLocaleDateString()}</span>
                      )}
                    </div>
                    <p className="text-xs text-muted-foreground mt-1 line-clamp-1">
                      {article.excerpt || article.description || '暂无摘要'}
                    </p>
                  </div>
                </div>
                
                <DropdownMenu>
                  <DropdownMenuTrigger asChild>
                    <Button variant="ghost" size="icon" className="h-8 w-8">
                      <MoreHorizontal className="h-4 w-4" />
                    </Button>
                  </DropdownMenuTrigger>
                  <DropdownMenuContent align="end">
                    <DropdownMenuItem onClick={() => router.push(`/knowledge/${article.id}`)}>
                      <Eye className="h-4 w-4 mr-2" />
                      查看
                    </DropdownMenuItem>
                    <DropdownMenuItem onClick={() => router.push(`/knowledge/${article.id}/edit`)}>
                      <Edit className="h-4 w-4 mr-2" />
                      编辑
                    </DropdownMenuItem>
                    <DropdownMenuItem 
                      onClick={() => updateArticleStatus(
                        article.id, 
                        article.status === 'PUBLISHED' ? 'DRAFT' : 'PUBLISHED'
                      )}
                      disabled={isSubmitting}
                    >
                      <CheckCircle className="h-4 w-4 mr-2" />
                      {article.status === 'PUBLISHED' ? '设为草稿' : '发布'}
                    </DropdownMenuItem>
                    <DropdownMenuItem 
                      className="text-destructive"
                      onClick={() => deleteArticle(article.id)}
                      disabled={isSubmitting}
                    >
                      <Trash2 className="h-4 w-4 mr-2" />
                      删除
                    </DropdownMenuItem>
                  </DropdownMenuContent>
                </DropdownMenu>
              </div>
            ))}
          </div>
        )}
      </CompactCard>
    </CompactLayout>
  )
}
